package com.ubadong.studentmng.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {

	private static String driverclass;
	private static String url;
	private static String userName;
	private static String passwd;
	
	//静态块，仅仅是在第一次访问的时候，初始化一次，以后不再初始化
	static{
		try {
			Properties pro = new Properties();
			InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("/jdbc.properties");
			pro.load(in);
			
			driverclass = pro.getProperty("jdbc.driverclass");
			url = pro.getProperty("jdbc.url");
			userName = pro.getProperty("jdbc.username");
			passwd = pro.getProperty("jdbc.passwd");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection(){
		//2、获取数据库连接
		Connection conn=null;
		try {
			//1、连接数据库第一步，要加载驱动程序（这样的方式用的多）
			Class.forName(driverclass);
			conn = DriverManager.getConnection(url, userName, passwd);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return conn;
	}
	
	public static void close(ResultSet rs, Statement st, Connection conn){

		//注意：资源要顺序关闭
		try {
			if(rs != null){
				rs.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

		//注意：资源要顺序关闭
		try {
			if(st != null){
				st.close();
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

		//注意：资源要顺序关闭
		try {
			if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
